package com.cxx.home.service.impl;

import com.cxx.home.dto.task.TaskDto;
import com.cxx.home.entity.Task;
import com.cxx.home.mapper.TaskMapper;
import com.cxx.home.service.QuartzService;
import com.cxx.home.service.TaskService;
import jakarta.annotation.Resource;
import org.quartz.JobKey;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class TaskServiceImpl implements TaskService {
    @Resource
    private TaskMapper taskMapper;

    @Resource
    private QuartzService quartzService;

    @Override
    public TaskDto queryTaskById(Long id) {
        Task task = taskMapper.selectById(id);
        TaskDto taskDto = new TaskDto();
        taskDto.setType(task.getType());
        taskDto.setContent(task.getContent());
        taskDto.setExecuteTime(task.getExecuteTime());
        taskDto.setCronExpression(task.getCronExpression());

        return taskDto;
    }

    @Override
    public Long addTask(TaskDto taskDto) {
        Task newTask = new Task();
        BeanUtils.copyProperties(taskDto, newTask);

        taskMapper.insert(newTask);
        quartzService.createQuartzTask(newTask);
        return newTask.getId();
    }

    @Override
    public Boolean updateTask(Long id, TaskDto taskDto) {
        Task newTask = new Task();
        BeanUtils.copyProperties(taskDto, newTask);

        newTask.setId(id);
        quartzService.updateQuartzTask(newTask);
        return taskMapper.updateById(newTask) == 1;
    }

    @Override
    public Boolean deleteTask(Long id) {
        quartzService.deleteQuartzTask(new JobKey(id.toString()));
        return taskMapper.deleteById(id) == 1;
    }
}
